import { GlobalData } from '/store/state'
import { $event } from '/utils'
import { currencyApi } from '/api/currency'
import { getServer } from '/store/mutations'
import { getDomoUser } from '/store/actions'

Page({
  data: {
    title: '充值',
    access: GlobalData.access,
    currencyName: GlobalData.currencyName,
    navigationHeight: GlobalData.navigationHeight,
    rechargeRatio: GlobalData.currency.settings['recharge-ratio'],
    pointsList: [100, 200, 300, 400, 500, 600],
    amount: 100,
    payLock: false,
  },
  onShow() {
    const { settings } = GlobalData.currency
    const pointsList = settings['recharge-options']
      .split(',')
      .map((v) => parseInt(v))
      .filter((v) => !!v)

    if (pointsList.length) {
      this.setData({
        pointsList: pointsList,
        amount: pointsList[0],
      })
    }

    $event.on('after:boot', this, () => {
      this.getPosition()
    })
    this.getPosition()
  },
  getPosition() {
    this.setData({
      access: GlobalData.access,
      currencyName: GlobalData.currencyName,
      navigationHeight: GlobalData.navigationHeight,
      rechargeRatio: GlobalData.currency.settings['recharge-ratio'],
    })
  },
  /** 点击选择价格 */
  changePrice(e: WechatMiniprogram.CustomEvent) {
    const {
      currentTarget: {
        dataset: { item },
      },
    } = e

    this.setData({
      amount: +item,
    })
  },
  /** 输入框输入价格 */
  inputPrice(e: WechatMiniprogram.CustomEvent) {
    const {
      detail: { value },
    } = e
    this.setData({
      amount: +value * 100,
    })
  },
  /** 充值 */
  async pay() {
    if (this.data.payLock) return

    const { settings } = GlobalData.currency
    let errMsg = ''
    if (this.data.amount < +settings['recharge-min']) {
      errMsg = `最少充值${+settings['recharge-min'] / 100}元`
    }
    // recharge-max 单笔最高充值额度  单位人民币分
    if (this.data.amount > +settings['recharge-max']) {
      errMsg = `最多充值${+settings['recharge-max'] / 100}元`
    }
    if (errMsg) {
      wx.showToast({ title: errMsg, icon: 'none' })
      return
    }

    await this.payLock(true)

    try {
      const res = await currencyApi.rechargeCurrency(
        +this.data.amount,
        wx.getStorageSync(`${getServer()}/openId`).data,
      )
      wx.requestPayment({
        ...res.data,
        success: async () => {
          await this.payLock(false)
          this.payShowToast(true)
          getDomoUser()
        },
        fail: async () => {
          await this.payLock(false)
          this.payShowToast(false)
        },
      })
    } catch (error) {
      await this.payLock(false)
      wx.showToast({ title: `${error.data.message}`, icon: 'none' })
    }
  },

  payLock(status: boolean) {
    this.setData({ payLock: status })

    return new Promise<void>((resolve) => {
      if (status) {
        wx.showLoading({
          mask: true,
          title: '支付中...',
          complete: () => resolve(),
        })
      } else {
        wx.hideLoading({
          complete: () => resolve(),
        })
      }
    })
  },

  payShowToast(success: boolean) {
    this.setData({
      payToast: true,
      paySuccess: success,
    })
  },
  closePayShow() {
    this.setData({ payToast: false })
  },
  toblack() {
    wx.navigateBack({ delta: 1 })
  },
})
